package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"time"

	"./ccpm/remotecon"
	"./ccpm/utilgo/utilpath"
)

const zipName = "web.zip"

// json for buildparams
type buildParams struct {
	Outpath    string
	Projpath   string
	Sshkey     string
	Sshpwd     string
	Remotepath string
}

func fmtlog(logstr string) {
	ctime := time.Now()
	fmt.Printf("[build]%s:%s\n", ctime.String(), logstr)
}

func getJSONParams(fsrc string) *buildParams {
	var c buildParams
	f, err := os.Open(fsrc)
	if err != nil {
		log.Fatalln(err)
	}
	ret, err := ioutil.ReadAll(f)
	if err != nil {
		log.Fatalln(err)
	}
	err = json.Unmarshal(ret, &c)
	if err != nil {
		log.Fatalln(err)
	}
	return &c
}

var fsrcConfig string

func init() {
	flag.StringVar(&fsrcConfig, "c", "", "json-file write with params's relpath for build.")
}

func zipUpload(fpath string, sshkey string, sshpwd string, remotedir string) {
	cpath, _ := os.Getwd()
	ziptar := path.Join(cpath, zipName)
	utilpath.ZipDir(fpath, ziptar)
	remoteinc := &remotecon.RemoteCon{}
	issuc := remoteinc.Connect(sshkey, sshpwd)
	if issuc {
		remoteinc.UploadFile(ziptar, remotedir)
		remoteinc.RunCmd(fmt.Sprintf("cd %s && unzip -o ./%s", remotedir, zipName))
	}
}

func main() {
	flag.Parse()
	if fsrcConfig == "" {
		flag.PrintDefaults()
		log.Fatalln("input the must-require param!")
	}
	// read json
	params := getJSONParams(fsrcConfig)
	fmt.Println(params.Projpath)
	fmt.Println(params.Outpath)
	// execute
	fmtlog("start build...")
	pwd, _ := os.Getwd()
	h5path, _ := filepath.Abs(path.Join(pwd, params.Projpath))
	distpath, _ := filepath.Abs(path.Join(pwd, params.Outpath))
	os.Chdir(h5path)
	fmtlog("build target...")
	ret := exec.Command("npm", "run", "build")
	_, err := ret.CombinedOutput()
	if err != nil {
		log.Fatalln(err)
	}
	fmtlog("build suc!")
	fmtlog("packing...")
	// os.Chdir(distpath)
	zipUpload(distpath, params.Sshkey, params.Sshpwd, params.Remotepath)

}
